package com.changgou.controller;

import com.alibaba.fastjson.JSON;
import com.changgou.service.WeiXinPayService;
import com.github.wxpay.sdk.WXPayUtil;
import entity.Result;
import entity.StatusCode;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 秦川熙
 */
@RestController
@RequestMapping(value = "/weixin/pay")
@CrossOrigin
public class WeiXinPayController {

    @Autowired
    private WeiXinPayService weiXinPayService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    /**
     * 创建二维码
     * @param parameter
     * @return
     */
    @GetMapping(value = "/create/native")
    public Result createNative(@RequestParam Map<String, String> parameter) {
        Map<String, String> resultMap = weiXinPayService.createNative(parameter);
        return new Result(true, StatusCode.OK, "创建二维码预付订单成功", resultMap);
    }

    /**
     * 查询支付状态
     * @param outtradeno
     * @return
     */
    @GetMapping(value = "/status/query")
    public Result queryStatus(String outtradeno) {
        Map<String, String> resultMap = weiXinPayService.queryPayStatus(outtradeno);
        return new Result(true, StatusCode.OK, "查询状态成功", resultMap);
    }

    /**
     * 支付回调
     * @param request
     * @return
     */
    @RequestMapping(value = "/notify/url")
    public String notifyUrl(HttpServletRequest request) {
        InputStream inputStream;

        try {
            //读取支付回调数据
            inputStream = request.getInputStream();
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            outStream.close();
            inputStream.close();
            //将支付回调数据转换成xml字符串
            String result = new String(outStream.toByteArray(), "utf-8");
            //将xml字符串转换成Map结构、
            Map<String, String> map = WXPayUtil.xmlToMap(result);
            //获取所有的数据
            String attach = map.get("attach");
            Map<String, String> parameter = JSON.parseObject(attach, Map.class);

            //发送消息
            rabbitTemplate.convertAndSend(parameter);

            //响应数据设置
            Map respMap = new HashMap();
            respMap.put("return_code", "SUCCESS");
            respMap.put("return_msg", "OK");
            return WXPayUtil.mapToXml(respMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
